package com.itlong.cloud.intercept;

import com.itlong.cloud.POJO.PO.AppRobotOperateLogPO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.noncore.commons.IRobotLoginLogServiceClient;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <desc>
 *      机器人登录日志拦截器
 * </desc>
 *
 * @createDate 2018/10/15
 */
@Aspect
@Component
public class RobotLoginLogIntercept {

    // 定义一个切入点
    @Pointcut("execution(* com.itlong.cloud.controller.robot.*.*(..))")
    public void excudeService(){}

    @Autowired
    private IRobotLoginLogServiceClient iRobotLoginLogServiceClient;

    @Value("${" + PlatformConstants.APP_USER_TOKEN_KEY + "}")
    private String APP_USER_TOKEN_KEY;

    /**
     * <desc>
     *      机器人登陆日志拦截器
     * </desc>
     *
     * @param thisJoinPoint AOP接入点
     * @param loggerInfo 日志注解对象
     * @throws Exception
     * @author wangzhi
     * @createDate 2018/10/15
     */
    @After("excudeService() && @annotation(loggerInfo)")
    public void twiceAsOld(JoinPoint thisJoinPoint, LoggerInfo loggerInfo) throws Exception{
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Date nowTime = new Date();
        if ("robotLogin".equals(loggerInfo.operateDesc()) && request.getAttribute("appRobotAccountId") != null) {
            AppRobotOperateLogPO appRobotOperateLogPO = new AppRobotOperateLogPO();
            appRobotOperateLogPO.setAppRobotOperateLogId(LogicIdUtil.bussinessId());
            appRobotOperateLogPO.setAppRobotAccountId(request.getAttribute("appRobotAccountId").toString());
            appRobotOperateLogPO.setAccount(request.getParameter("account"));
            String city = request.getParameter("city");
            appRobotOperateLogPO.setLocation(city);
            String ip = HttpProtocolUtil.getIpAddr(request);
            appRobotOperateLogPO.setIpAddress(ip);
            appRobotOperateLogPO.setOperateType(1);
            appRobotOperateLogPO.setStatus(DataStatusEnum.NORMAL.getType());
            appRobotOperateLogPO.setCreateTime(nowTime);
            appRobotOperateLogPO.setUpdateTime(nowTime);
            iRobotLoginLogServiceClient.save(appRobotOperateLogPO);
        }
    }

}
